package cn.com.inossem.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.util.Base64;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.foxykeep.datadroid.requestmanager.Request;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.util.List;

import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.db.DatabaseHelper;
import cn.com.inossem.model.DatePicjerInfo;
import cn.com.inossem.model.EducationInfoBean;
import cn.com.inossem.model.SkillsInfoBean;
import cn.com.inossem.model.UserInfo;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.ActivityStackControlUtil;
import cn.com.inossem.utils.SystemPictureUtil;
import cn.com.inossem.utils.Utils;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;


/**
 * 我的账户
 * <p>
 * <p>
 * detailed comment
 *
 * @author szc 2015-8-24
 * @see
 * @since 1.0
 */
@RuntimePermissions
public class MyInformationActivity extends RequestActivity {

	// private StatusEnum statusEnum;

	RelativeLayout model, portrait, zhanghao, professional, education, jingyan,
			homedizhi, nickname, truename, email, hangye, workyear, sapyear,
			xingbie, chusheng;

	TextView homedizhitext, nicknametext, truenametext, emailtext,
			zhanghaotext, hangyetext, workyeartext, sapyeartext, modeltext,
			xiangmujingyan, xingbietext, chushengtext;

	ImageView touxiang, back;
	TextView educationtext, professionaltext;
	DatePicjerInfo mDatePicker;
	private Uri uri;
	private TextView bankName, bankNum;
	private Uri localUri;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main_tab_layout);
		initView();

	}

	@Override
	public void onDestroy() {
		ActivityStackControlUtil.remove(this);
		super.onDestroy();
	}

	private void initView() {
		mDatePicker = new DatePicjerInfo();
		touxiang = (ImageView) this.findViewById(R.id.touxiang);

		back = (ImageView) this.findViewById(R.id.back);
		back.setOnClickListener(this);

		model = (RelativeLayout) this.findViewById(R.id.model);
		model.setOnClickListener(this);

		portrait = (RelativeLayout) this.findViewById(R.id.portrait);
		portrait.setOnClickListener(this);

		zhanghao = (RelativeLayout) this.findViewById(R.id.zhanghao);// 账号
		zhanghao.setOnClickListener(this);

		nickname = (RelativeLayout) this.findViewById(R.id.nickname);// 昵称
		nickname.setOnClickListener(this);

		truename = (RelativeLayout) this.findViewById(R.id.truename);// 真实姓名
		truename.setOnClickListener(this);

		email = (RelativeLayout) this.findViewById(R.id.email);// 邮箱
		email.setOnClickListener(this);

		homedizhi = (RelativeLayout) this.findViewById(R.id.homedizhi);// 家所在地
		homedizhi.setOnClickListener(this);

		professional = (RelativeLayout) this.findViewById(R.id.professional);
		professional.setOnClickListener(this);

		education = (RelativeLayout) this.findViewById(R.id.education);
		education.setOnClickListener(this);

		jingyan = (RelativeLayout) this.findViewById(R.id.jingyan);
		jingyan.setOnClickListener(this);

		workyear = (RelativeLayout) this.findViewById(R.id.workyear);
		workyear.setOnClickListener(this);

		sapyear = (RelativeLayout) this.findViewById(R.id.sapyear);
		sapyear.setOnClickListener(this);

		hangye = (RelativeLayout) this.findViewById(R.id.hangye);
		hangye.setOnClickListener(this);

		xingbie = (RelativeLayout) this.findViewById(R.id.xingbie);
		xingbie.setOnClickListener(this);

		chusheng = (RelativeLayout) this.findViewById(R.id.chusheng);
		chusheng.setOnClickListener(this);

		xingbietext = (TextView) this.findViewById(R.id.xingbietext);// 性别
		xingbietext
				.setText(Utils.messageInfo.userInfo.getSex().equals("0") ? "男"
						: "女");

		chushengtext = (TextView) this.findViewById(R.id.chushengtext);// 出生日期
		System.out.println(Utils.messageInfo.userInfo.getBirthday()
				+ "Utils.messageInfo.userInfo.getBirthday().length():"
				+ Utils.messageInfo.userInfo.getBirthday().length());
		chushengtext.setText(Utils.messageInfo.userInfo.getBirthday());
		if (Utils.messageInfo.userInfo.getBirthday().length() > 0) {
			String[] timesText = Utils.messageInfo.userInfo.getBirthday()
					.split("-");
			mDatePicker.year = Integer.parseInt(timesText[0]);
			mDatePicker.month = Integer.parseInt(timesText[1]) - 1;
			mDatePicker.dayofmonth = Integer.parseInt(timesText[2]);
		}

		homedizhitext = (TextView) this.findViewById(R.id.homedizhitext);// 家所在地
		if (Utils.messageInfo.userInfo.getHomeAddress() != 0)
			homedizhitext.setText(selectData_info("t_areas", "area_id="
					+ Utils.messageInfo.userInfo.getHomeAddress()));
		zhanghaotext = (TextView) this.findViewById(R.id.zhanghaotext);// 账号
		zhanghaotext.setText(Utils.messageInfo.userInfo.getUsername());
		nicknametext = (TextView) this.findViewById(R.id.nicknametext);// 昵称
		nicknametext.setText(Utils.messageInfo.userInfo.getNickname());
		truenametext = (TextView) this.findViewById(R.id.truenametext);// 真实姓名
		truenametext.setText(Utils.messageInfo.userInfo.getTruename());
		emailtext = (TextView) this.findViewById(R.id.emailtext);// 邮箱
		emailtext.setText(Utils.messageInfo.userInfo.getEmail());

		modeltext = (TextView) this.findViewById(R.id.modeltext);// 模块
		List<SkillsInfoBean> skillsInfoBeanList = Utils.messageInfo.userInfo.getUserSkill();
		StringBuilder modeltextBuilder = new StringBuilder();
		if ((skillsInfoBeanList != null) && (skillsInfoBeanList.size() > 0)) {
			modeltextBuilder.append(selectName_info("t_dictionary", "id=" + skillsInfoBeanList.get(0).getSkillID()));
			modeltextBuilder.append("等").append(skillsInfoBeanList.size()).append("个");
		} /*else {
			modeltextBuilder.append("等0个");
		}*/
		modeltext.setText(modeltextBuilder.toString());

		hangyetext = (TextView) this.findViewById(R.id.hangyetext);// 行业

		System.out.println("asdkaskldjsakljdasl:"
				+ Utils.messageInfo.userInfo.getIndustry());
		if (!Utils.messageInfo.userInfo.getIndustry().equals(""))
			hangyetext.setText(selecthangye_info("t_dictionary",
					Utils.messageInfo.userInfo.getIndustry()));

		educationtext = (TextView) this.findViewById(R.id.educationtext);// 教育
		List<EducationInfoBean> educationInfoBeanList = Utils.messageInfo.userInfo.getUserEducation();
		StringBuilder educationtextBuilder = new StringBuilder();
		if ((educationInfoBeanList != null) && (educationInfoBeanList.size() > 0)) {
			educationtextBuilder.append(educationInfoBeanList.get(0).getSchoolName());
			educationtextBuilder.append("等").append(educationInfoBeanList.size()).append("个");
		} /*else {
			educationtextBuilder.append("等0个");
		}*/
		educationtext.setText(educationtextBuilder.toString());

		professionaltext = (TextView) this.findViewById(R.id.professionaltext);// 职业背景strUserEducation
		professionaltext.setText(Utils.messageInfo.userInfo.getStrUserBg());

		xiangmujingyan = (TextView) this.findViewById(R.id.xiangmujingyan);// 项目经验
		xiangmujingyan.setText(Utils.messageInfo.userInfo.getStrProjectExp());

		workyeartext = (TextView) this.findViewById(R.id.workyeartext);// 工作年限
		workyeartext.setText(Utils.messageInfo.userInfo.getWorkYear() + "年");

		sapyeartext = (TextView) this.findViewById(R.id.sapyeartext);// sap年限
		sapyeartext.setText(Utils.messageInfo.userInfo.getSapYear() + "年");
		// "t_areas", "area_id="+

		UserInfo ui = Utils.messageInfo.userInfo;
		if (!ui.getImageData().equals("")) {
			touxiang.setBackgroundDrawable(new BitmapDrawable(Utils
					.toRoundCorner(stringtoBitmap(ui.getImageData()), 50)));
		}
		findViewById(R.id.layout_bankName).setOnClickListener(this);
		bankName = (TextView) findViewById(R.id.bankName);
		if (TextUtils.isEmpty(ui.getBankType())) {
			bankName.setText("请选择");
		} else {
			bankName.setText(ui.getBankType());
		}
		findViewById(R.id.layout_bankNum).setOnClickListener(this);
		bankNum = (TextView) findViewById(R.id.bankNum);
		if (TextUtils.isEmpty(ui.getBankAccount())) {
			bankNum.setText("请输入");
		} else {
			bankNum.setText(ui.getBankAccount());
		}
	}

	private String selecthangye_info(String tabname, String id) {
		String name = "";
		String[] strid = {""};
		if (id.equals(""))
			return "";
		if (id.contains(","))
			strid = id.split(",");
		else
			strid[0] = id;
		DatabaseHelper dh = new DatabaseHelper(this);
		SQLiteDatabase db = dh.getReadableDatabase();
		Cursor cursor = db.query(tabname, null, "pid = 108 and id = "
				+ strid[0], null, null, null, null);
		if (cursor.moveToFirst()) {
			name = cursor.getString(cursor.getColumnIndex("name_cn"));
		}
		if (strid.length > 1)
			name += "等" + strid.length + "个";
		cursor.close();
		db.close();
		dh.close();
		return name;
	}

	private String selectData_info(String tabname, String selection) {
		String name = "";
		DatabaseHelper dh = new DatabaseHelper(this);
		SQLiteDatabase db = dh.getReadableDatabase();
		Cursor cursor = db.query(tabname, null, selection, null, null, null,
				null);
		if (cursor.moveToFirst()) {
			name = cursor.getString(cursor.getColumnIndex("area_name"));
		}
		cursor.close();
		db.close();
		dh.close();
		return name;
	}

	private String selectName_info(String tabname, String selection) {
		String name = "";
		DatabaseHelper dh = new DatabaseHelper(this);
		SQLiteDatabase db = dh.getReadableDatabase();
		Cursor cursor = db.query(tabname, null, selection, null, null, null,
				null);
		if (cursor.moveToFirst()) {
			name = cursor.getString(cursor.getColumnIndex("name_cn"));
		}
		cursor.close();
		db.close();
		dh.close();
		return name;
	}

	@Override
	public Request getInitialRequest() {
		return null;

	}

	@Override
	public void onRequestSucess(Request request, Bundle bundle) {

	}

	@Override
	public void onRequestError(int exceptionType) {

	}

	public int getContentViewId() {
		return R.layout.myinformation_layout;

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (v.getId()) {
			case R.id.next:
				break;
			case R.id.chusheng:
				DatePickerDialog datePickerDialog = new DatePickerDialog(this,
						Datelistener, mDatePicker.getYear(),
						mDatePicker.getMonth(), mDatePicker.getDayofmonth());
				datePickerDialog.show();
				break;
			case R.id.xingbie:
				showDialog(XINGBIE_DIALOG);
				break;
			case R.id.back:
				setResult(99);
				finish();
				break;
			case R.id.jingyan:
				intent = new Intent(this, ProjectGongsiNameActivity.class);
				startActivityForResult(intent, 999);
				break;
			case R.id.education:
				intent = new Intent(this, EducationActivity.class);
				startActivityForResult(intent, 999);
				break;
			case R.id.professional:
				intent = new Intent(this, ProfessionalActivity.class);
				startActivityForResult(intent, 999);
				break;
			case R.id.zhanghao:
				intent = new Intent(this, AddAccountActivity.class);
				startActivityForResult(intent, 999);
				break;
			case R.id.model:
				intent = new Intent(this, ModelCenterActivity.class);
				startActivityForResult(intent, 999);
				break;
			case R.id.portrait:
				showDialog(COMMON_DIALOG);
				break;
			case R.id.homedizhi:
				intent = new Intent(this, CityActivity.class);
				intent.putExtra("type", 21);
				startActivityForResult(intent, 999);
				break;
			case R.id.nickname:
				intent = new Intent(this, NameActivity.class);
				intent.putExtra("type", 100);
				startActivityForResult(intent, 999);
				break;
			case R.id.truename:
				intent = new Intent(this, NameActivity.class);
				intent.putExtra("type", 101);
				startActivityForResult(intent, 999);
				break;
			case R.id.email:
				intent = new Intent(this, NameActivity.class);
				intent.putExtra("type", 102);
				startActivityForResult(intent, 999);
				break;
			case R.id.hangye:
				intent = new Intent(this, RetrieveItemActivity.class);
				intent.putExtra("type", 2);
				intent.putExtra("isflag", true);
				System.out.println("Utils.messageInfo.userInfo.getIndustry():"
						+ Utils.messageInfo.userInfo.getIndustry());
				intent.putExtra("idstr", Utils.messageInfo.userInfo.getIndustry());
				startActivityForResult(intent, 999);
				break;
			case R.id.workyear:
				intent = new Intent(this, NameActivity.class);
				intent.putExtra("type", 106);
				startActivityForResult(intent, 999);
				break;
			case R.id.sapyear:
				intent = new Intent(this, NameActivity.class);
				intent.putExtra("type", 107);
				startActivityForResult(intent, 999);
				break;
			case R.id.layout_bankName:
				intent = new Intent(this, SelectBankActivity.class);
				intent.putExtra("type", 110);
				startActivityForResult(intent, 999);
				break;
			case R.id.layout_bankNum:
				intent = new Intent(this, NameActivity.class);
				intent.putExtra("type", 109);
				startActivityForResult(intent, 999);
				break;
			default:
				break;
		}
	}

	final int COMMON_DIALOG = 1;
	final int XINGBIE_DIALOG = 2;

	protected Dialog onCreateDialog(int id) { // 重写onCreateDialog方法
		Dialog dialog = null; // 声明一个Dialog对象用于返回
		switch (id) { // 对id进行判断
			case COMMON_DIALOG:
				Builder b = new AlertDialog.Builder(this, R.style.AlertDialog);
				b.setTitle(R.string.dialogTitle); // 设置对话框的标题
				b.setMessage(R.string.fangshi); // 设置对话框的显示内容
				b.setPositiveButton( // 添加按钮
						R.string.xiangce, new DialogInterface.OnClickListener() { // 为按钮添加监听器
							public void onClick(DialogInterface dialog, int which) {
								MyInformationActivityPermissionsDispatcher.setViewChocieWithCheck(MyInformationActivity.this);
							}
						});
				b.setNegativeButton( // 添加按钮
						R.string.paiyizhang, new DialogInterface.OnClickListener() { // 为按钮添加监听器
							public void onClick(DialogInterface dialog, int which) {
								MyInformationActivityPermissionsDispatcher.setPaizhaoChocieWithCheck(MyInformationActivity.this);
							}
						});
				dialog = b.create(); // 生成Dialog对象
				break;
			case XINGBIE_DIALOG:
				b = new AlertDialog.Builder(this, R.style.AlertDialog);
				b.setTitle(R.string.dialogTitle); // 设置对话框的标题
				b.setTitle("请选择性别"); // 设置对话框的标题
				b.setPositiveButton( // 添加按钮
						"男", new DialogInterface.OnClickListener() { // 为按钮添加监听器
							public void onClick(DialogInterface dialog, int which) {
								xingbietext.setText("男");
								Utils.messageInfo.userInfo.setSex("0");
								launchRequest(WooRequestFactory.updatePersonal(
										"sex", "0"));
							}
						});
				b.setNegativeButton( // 添加按钮
						"女", new DialogInterface.OnClickListener() { // 为按钮添加监听器
							public void onClick(DialogInterface dialog, int which) {
								xingbietext.setText("女");
								Utils.messageInfo.userInfo.setSex("1");
								launchRequest(WooRequestFactory.updatePersonal(
										"sex", "1"));
							}
						});
				dialog = b.create(); // 生成Dialog对象
				break;
			default:
				break;
		}
		return dialog; // 返回生成Dialog的对象
	}

	/**
	 * 相册选择
	 */
	@NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
	public void setViewChocie() {
		SystemPictureUtil.getPictureFromAlbum(this, 0);
	}

	/**
	 * 拍照
	 */
	@NeedsPermission(Manifest.permission.CAMERA)
	public void setPaizhaoChocie() {
		localUri = SystemPictureUtil.getPictureFromCamera(this, CAMERA_WITH_DATA);
	}

	BitmapDrawable drawable;
	Bitmap cameraBitmap;
	private static final int PHOTO_REQUEST_CUT = 3020;
	private static final int CAMERA_WITH_DATA = 3021;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		System.out.println(requestCode + "resultCode:" + resultCode);
		switch (requestCode) {
			case 0://相册选择返回
				if (resultCode != -1)
					return;
				Uri originalUri = data.getData();
				MyInformationActivityPermissionsDispatcher.startPhotoZoomWithCheck(this, originalUri);
				break;
			case CAMERA_WITH_DATA://拍照返回
				if (resultCode != -1)
					return;
				MyInformationActivityPermissionsDispatcher.startPhotoZoomWithCheck(this, localUri);
				break;
			case PHOTO_REQUEST_CUT://剪裁返回
				if (resultCode != -1)
					return;
				try {
					cameraBitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(localUri));
					if (cameraBitmap != null) {
						String imagestr = bitmaptoString(cameraBitmap);
						Utils.messageInfo.userInfo.setImageData(imagestr);
						touxiang.setBackgroundDrawable(new BitmapDrawable(Utils.toRoundCorner(cameraBitmap, 50)));
						launchRequest(WooRequestFactory.updatePersonal("image", imagestr));
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				break;
			default:
				break;
		}
		switch (resultCode) {
			case 2:
				String name = data.getStringExtra("name");
				String num = data.getStringExtra("num");
				String value = data.getStringExtra("value");
				Utils.messageInfo.userInfo.setIndustry(value);
				hangyetext.setText(name + num);
				break;
			case 21:
				int id = data.getIntExtra("id", 0);
				name = data.getStringExtra("name");
				System.out.print(name);
				homedizhitext.setText(name);
				if (Utils.messageInfo != null)
					Utils.messageInfo.userInfo.setHomeAddress(id);
				break;
			case 97:// 技能
				name = data.getStringExtra("name");
				Utils.messageInfo.userInfo.setStrUserSkill(name);
				modeltext.setText(name);
				break;
			case 99:// 账号
				name = data.getStringExtra("name");
				Utils.messageInfo.userInfo.setTruename(name);
				zhanghaotext.setText(name);
				break;
			case 100:
				name = data.getStringExtra("name");
				Utils.messageInfo.userInfo.setNickname(name);
				nicknametext.setText(name);
				break;
			case 101:
				name = data.getStringExtra("name");
				Utils.messageInfo.userInfo.setTruename(name);
				truenametext.setText(name);
				break;
			case 102:
				name = data.getStringExtra("name");
				Utils.messageInfo.userInfo.setEmail(name);
				emailtext.setText(name);
				break;
			case 103:// 教育
				name = data.getStringExtra("name");
				Utils.messageInfo.userInfo.setStrUserEducation(name);
				educationtext.setText(name);
				break;
			case 104:// 职业背景
				name = data.getStringExtra("name");
				Utils.messageInfo.userInfo.setStrUserBg(name);
				professionaltext.setText(name);
				break;
			case 105:// 项目经验
				name = data.getStringExtra("name");
				Utils.messageInfo.userInfo.setStrProjectExp(name);
				xiangmujingyan.setText(name);
				break;
			case 106:// 工作年限
				name = data.getStringExtra("name");
				Utils.messageInfo.userInfo.setWorkYear(name);
				workyeartext.setText(name + "年");
				break;
			case 107:// sap年限
				name = data.getStringExtra("name");
				Utils.messageInfo.userInfo.setSapYear(name);
				sapyeartext.setText(name + "年");
				break;
			case 109:
				name = data.getStringExtra("name");
				bankNum.setText(name);
				Utils.messageInfo.userInfo.setBankAccount(name);
				break;
			case 110:
				name = data.getStringExtra("name");
				bankName.setText(name);
				Utils.messageInfo.userInfo.setBankType(name);
				break;
		}
	}

	@NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
	public void startPhotoZoom(Uri uri) {
		localUri = SystemPictureUtil.getPictureFromClip(this, PHOTO_REQUEST_CUT, uri);
	}

	public String bitmaptoString(Bitmap bitmap) {
		// 将Bitmap转换成字符串
		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return string;
	}

	public Bitmap stringtoBitmap(String string) {
		// 将字符串转换成Bitmap类型
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(99);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {
		/**
		 * params：view：该事件关联的组件 params：myyear：当前选择的年 params：monthOfYear：当前选择的月
		 * params：dayOfMonth：当前选择的日
		 */
		@Override
		public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
			// 修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
			mDatePicker.updateDate(myyear, monthOfYear, dayOfMonth);
			// 更新日期
			updateDate();
		}

		// 当DatePickerDialog关闭时，更新日期显示
		private void updateDate() {
			// 在TextView上显示日期
			String str = mDatePicker.getYear() + "-"
					+ (mDatePicker.getMonth() + 1) + "-"
					+ mDatePicker.getDayofmonth();
			chushengtext.setText(str);
			Utils.messageInfo.userInfo.setBirthday(str);
			launchRequest(WooRequestFactory.updatePersonal("birthday", str));
		}
	};

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		MyInformationActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
	}
}
